import time

import jenkins
import os
import platform
import requests
import requests.utils

'''
gx--excuteJob：自动触发jenkins中的任务，待到jenkins中任务开始执行返回对应的console URL
--cancelJob：停止jenkins中的执行任务
paramName为jenkins中配置的参数和构建项目中的参数名称
'''


def getJenkinsDir():
    '''
    获取Jenkins目录
    '''
    global d
    sys = platform.system()
    if sys == "Windows":
        d = '''/opt/tomcat7/webapps/'''
    elif sys == "Linux":
        d = os.popen('echo $JENKINS_HOME').read()

    if d:
        d = d.strip()
        if d.endswith('/'):
            d += 'workspace'
        else:
            d = os.path.join(d, 'workspace')
        return d
    else:
        return False


class ExcuteJenkinsJob():

    def __init__(self, username='admin', password='123qwe'):
        from http import cookiejar

        self.username = username
        self.password = password
        self.jenkinsUrl = 'http://qa-ci.xxxxxx.com/'
        self.server = jenkins.Jenkins(self.jenkinsUrl, username=self.username, password=self.password)
        self.cookie = cookiejar.CookieJar()

    def excuteJob(self, jobName, branchName="origin/master"):
        import re
        try:
            self.server.build_job(jobName, parameters={"branchName": branchName})
            number = self.server.get_job_info(jobName)['lastBuild']['number']
            info = self.server.get_build_console_output(jobName, number)
            if info.endswith('Finished: SUCCESS\n'):
                # test = re.search('sacnStart: (.*?) scanEnd', info)
                # if test:
                return {"code": 1, "msg": "构建成功"}
            else:
                return {"code": 0, "msg": "构建失败"}
        except Exception as e:
            return {"code": 0, "msg": f"构建异常{e}"}

    def jenkinsLog(self, jobName="test_platform_api"):
        server = jenkins.Jenkins(url='https://qa-ci.xxxxxx.com/', username='admin', password='123qwe')
        number = server.get_job_info(jobName)['lastBuild']['number']
        info = server.get_build_console_output(jobName, number)
        return info

    def cancelJob(self, jobName, num):
        server = jenkins.Jenkins(self.jenkinsUrl, username=self.username, password=self.password)
        server.stop_build(name=jobName, number=num)

    def getJobList(self):
        return self.server.get_all_jobs()

    def getViews(self):
        return [i['name'] for i in self.server.get_views()]

    def getViewJobs(self, viewname):
        return [i['name'] for i in self.server.get_jobs(view_name=viewname)]

    def getAllJobs(self):
        return [i['name'] for i in self.server.get_all_jobs()]

    def getAllViewJobs(self):
        all = self.getViews()
        allViewJobs = {}
        for a in all:
            allViewJobs.update({a: self.getViewJobs(a)})
        return allViewJobs

    # 获取cookie
    def getcookies(self):
        rs = requests.session()
        rs.post("http://qa-ci.xxxxxx.com/j_spring_security_check",
                data={'j_username': "admin", "j_password": "123qwe", "from": "/", "Submit": "登录"})
        cookie = rs.headers
        # print(">>>>>>>", cookie["Set-Cookie"])
        # return requests.utils.dict_from_cookiejar(cookie)
        # return cookie["Set-Cookie"]
        return rs

    # 获取项目所有分支
    def getAllBranch(self, jobName):
        try:
            # res = requests.get(url="http://qa-ci.xxxxxx.com/crumbIssuer/api/json")
            # crumb = res.json()["crumb"]
            res = requests.get(
                url=f'http://qa-ci.xxxxxx.com/job/{jobName}/descriptorByName/net.uaznia.lukanus.hudson.plugins.gitparameter.GitParameterDefinition/fillValueItems?param=branchName')

            return res.json()
        except Exception as e:
            print("项目名不存在{}".format(e))
            return None


if __name__ == '__main__':
    job = ExcuteJenkinsJob()
    #     print(job.excuteJob("lpee-member-service", "origin/develop"))
    #     print(job.getcookies())
    #     a = job.getAllBranch("lpee-grade-service")
    #     print(time.time())
    #     print(job.jenkinsLog())
    # print(job.server.get_job_info("loyalty2-member"))
    print(job.getAllBranch("loyalty2-member"))
